var pomelo = require('pomelo');
var redis = require('redis');
var routeUtil = require('./app/util/routeUtil');
// var loadMysqlConfig = require('./app/components/loadMysqlConfig');
// var masterhaPlugin = require('pomelo-masterha-plugin');
var resetRedisData = require('./app/components/resetRedisData');
var httpServer = require('./app/components/httpServer');

/**
 * Init app for client.
 */
var app = pomelo.createApp();
app.set('name', 'yiwei-pomelo');

// app configuration
app.configure('production|development', 'connector', function () {
    app.set('connectorConfig',
        {
            connector: pomelo.connectors.hybridconnector,
            heartbeat: 3,
            disconnectOnTimeout: true,
            useDict: true,
            useProtobuf: true
        });
});

app.configure('production|development', 'gate', function () {
    // app.load(loadMysqlConfig, { interval: 500 });
    // 用于启动服务时从 mysql 载入游戏配置数据
    // app.load(loadMysqlConfig);
    // 用于游戏停服更新后，再次启动时，自动更新此前在线用户数据
    app.load(resetRedisData);
    app.set('connectorConfig',
        {
            connector: pomelo.connectors.hybridconnector,
            useProtobuf: true
        });
});

app.configure('production|development', 'bjl', function () {
    app.set('connectorConfig',
        {
            connector: pomelo.connectors.hybridconnector,
            useProtobuf: true
        });
});

app.configure('production|development', 'niuniu', function () {
    app.set('connectorConfig',
        {
            connector: pomelo.connectors.hybridconnector,
            useProtobuf: true
        });
});

app.configure('production|development', function () {
    // app.enable('systemMonitor');
    app.set('connectorConfig',
        {
            connector: pomelo.connectors.hybridconnector,
            useProtobuf: true
        });

    // route configures
    app.route('bjl', routeUtil.bjl);  // 定义了route之后，就实现了全局调用game服务器的负载均衡
    // 如果定义在某个服务器的配置中，那么就只是在那个服务器上调用game时候会使用负载均衡
    app.route('niuniu', routeUtil.niuniu);
});


function retryStrategy(options) {
    if (options.error && options.error.code === 'ECONNREFUSED') {
        // End reconnecting on a specific error and flush all commands with a individual error  服务器拒绝连接则不再重连
        throw 'redis error: The server refused the connection';
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
        // End reconnecting after a specific timeout and flush all commands with a individual error  重连持续一小时
        return new Error('Retry time exhausted');
    }
    if (options.times_connected > 100) {
        // 重连100次
        // End reconnecting with built in error
        return new Error('Retry times over');
    }
    // reconnect after 10ms  10ms之后就开始重连
    return 10;
}

// 获取mysqlConfig
app.loadConfig('mysql', app.getBase() + '/config/mysql.json');
var mysqlConfig = app.get('mysql');
var data_db_master = mysqlConfig.data_db_master;
var dbDataClient_master = require('./app/dao/mysqlData_master').init(data_db_master.host, data_db_master.name, data_db_master.user, data_db_master.password);
app.set('dbDataClient_master', dbDataClient_master);

// 读取redisConfig  // 设置redisUser, redisGame, redisCache 等三个 client到 app上
app.loadConfig('redis', app.getBase() + '/config/redis.json');
var redisConfig = app.get("redis");
var redis_user = redisConfig.redis_user;
var redis_game = redisConfig.redis_game;
var redis_cache = redisConfig.redis_cache;
// var redisUser = redis.createClient(redis_user['port'], redis_user['host'], {connect_timeout:1});  connect_timeout is deprecated, now use retry_strategy
var redisUser = redis.createClient(redis_user.port, redis_user.host, { retry_strategy: retryStrategy });
redisUser.on('error', function (error, response) {
    console.log('redis 错误！');
    throw new Error(error);
});

redisUser.select(redis_user.db);
var redisGame = redis.createClient(redis_game.port, redis_game.host, { retry_strategy: retryStrategy });
redisGame.on('error', function (error, response) {
    console.log(error);
});
redisGame.select(redis_game.db);
var redisCache = redis.createClient(redis_cache.port, redis_cache.host, { retry_strategy: retryStrategy });
redisCache.on('error', function (error, response) {
    console.log(error);
});
redisCache.select(redis_cache.db);
redisCache.flushdb();
app.set('redisUser', redisUser);
app.set('redisGame', redisGame);
app.set('redisCache', redisCache);

// start app
app.start();

process.on('uncaughtException', function (err) {
    console.error(' Caught exception: ' + err.stack);
    process.exit();
});
